﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Infrastructure
{
    public class SerializeHelper
    {
        public static string Serialize<T>(T t)
        {
            IFormatter obj = new BinaryFormatter();

            MemoryStream ms = new MemoryStream();
            obj.Serialize(ms, t);

            BinaryReader br = new BinaryReader(ms);
            ms.Position = 0;
            byte[] bs = br.ReadBytes((int)ms.Length);
            ms.Close();
            return Convert.ToBase64String(bs);
        }

        public static T Deserialize<T>(string str)
        {
            IFormatter obj = new BinaryFormatter();
            byte[] bs = Convert.FromBase64String(str);
            MemoryStream ms = new MemoryStream();
            ms.Write(bs, 0, bs.Length);
            ms.Position = 0;
            object o = obj.Deserialize(ms);
            ms.Close();

            return (T)o;
        }
    }
}
